题目说明
1 | 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 |
解题思路一
- LRU缓存机制,可以自行百度一下。
- 特点1,hash表读取数据
- 特点2,存在一个
keys序列,代表缓存的所有key,顺序按照最近的活跃度来排序,比如你刚刚用过key为1的值,那么1就会排在keys序列的第一位。当缓存超出的时候,会优先删除keys的末尾。
- 所以我们主要维护了一个hash,js中就是一个对象,用来存数据。一个序列也就是一个数组存keys。
- get:如果将get的key,位置置换到首位。并返回数据。
- put:将put设置的值的key,放在keys序列首位,判断是否超出,超出则删除最后一位。
代码实现一
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.obj = {};
this.objKeys = [];
this.limit = capacity;
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if (this.obj[key]) {
this.objKeys.splice(this.objKeys.indexOf(key), 1);
this.objKeys.unshift(key);
return this.obj[key];
} else {
return -1
}
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
this.obj[key] && this.objKeys.splice(this.objKeys.indexOf(key), 1);
this.objKeys.unshift(key);
this.obj[key] = value;
if (this.objKeys.length > this.limit) {
delete this.obj[this.objKeys[this.limit]];
this.objKeys.length -= 1;
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/